package com.zzwtel.autocode.beetl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;


import com.zzwtel.autocode.template.constants.TemplatePath;
import com.zzwtel.autocode.template.model.EntityModel;
import com.zzwtel.autocode.template.model.Property;
import com.zzwtel.autocode.util.FileUtil;
import com.zzwtel.autocode.util.HumpUtil;
import com.zzwtel.autocode.util.PathUtil;
import com.zzwtel.autocode.util.StrKit;

/**
 * @author  草原狼
 *
 * 2017年7月10日
 */

public class FeignServiceTemplate {
	/**
	 * 生成代码
	 * @param tm
	 */
	public void generate(EntityModel tm) {		
		try{
			//准备工作#######################
			String root = PathUtil.getTemplateRoot();
			FileResourceLoader resourceLoader = new FileResourceLoader(root,"utf-8");
			Configuration cfg = Configuration.defaultConfiguration();
			GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
			//Template t = gt.getTemplate("/html/@{entity_model}_edit_form.html");	
			Template t = gt.getTemplate(TemplatePath.SPRING_FEIGN_SERVICE_JAVA_FILE_TEMPLATE);
			
			String servicePkg = "com.zzwtec.interfaces.information.services";			
			String dtoPkg = "com.zzwtec.interfaces.information.dto";
			String applicationName = "AppName.ZZWTEC_INFORMATION";
			//绑定数据#######################
			t.binding("servicePkg", servicePkg);			
			t.binding("dtoPkg", dtoPkg);
			t.binding("applicationName", applicationName);
			
			String model = tm.getTable().getModel();			
			//首字母小写，驼峰命名
			t.binding("entityModel", model);
			//首字母大写，驼峰命名
			t.binding("EntityModel", StrKit.firstCharToUpperCase(model));
			//全部大写，下划线分割
			String _model = HumpUtil.underscoreName(model);
			t.binding("ENTITY_MODEL", _model);
			//全部小写，下划线分割			
			t.binding("entity_model", HumpUtil.toLowerCase(_model));	
			//绑定表名
			t.binding("tableName", tm.getTable().getName());
			//开始绑定sql语句
			t.binding("entityModel", model);
			
			
			List<Property> list = tm.getProps();
			for(Property prop : list){
				String str = prop.getJavaType();
				int pos = str.lastIndexOf(".") + 1;
				prop.setJavaType(prop.getJavaType().substring(pos));
			}
			
			
			//构造路径#######################			
			String data = t.render();			
			String out = PathUtil.getOutRoot();		
			Map<String,String> map = new HashMap<String,String>();
			//先写死路径吧
			map.put("pkg", pkg2Path(servicePkg));
			map.put("EntityModel", StrKit.firstCharToUpperCase(model)+"Service");
			String fileName = StringTemplate.getFileName(TemplatePath.ENTITY_JAVA_FILE_OUTPUT,map);		
			FileUtil.write(out+fileName, data);
			
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
	private String pkg2Path(String pkg){
		return pkg.replace(".", "/");
	}
}
